import { defaultDataType } from '../config';
import type { IColumn, ICategoryItem } from '../typings/index.d.ts'


function contentParser(content:string, type: number): IColumn {
  const [dataIndex, title] = content.split(/\,\s+\/\//)[0].split(' => ');
  const dataType = /字段类型:(\w+)/.exec(content)?.[1] || 'string';
  const labelKey = /展示字段:([\w\-]+)/.exec(content)?.[1] || '';
  const isFixed = /是否固定:(\w+)/.exec(content)?.[1] || 'false';
  const relationKey = /关联字段:(.*?);/.exec(content)?.[1] || '';
  const isSort = /是否排序:(\w+)/.exec(content)?.[1];
  const width = /宽度:(\d+)/.exec(content)?.[1] || 120;
  const disabled = /是否禁用:(\w+)/.exec(content)?.[1] || 'false';
  const color = /颜色:(rgba\(.+\))/.exec(content)?.[1] || '';
  const formatter = /格式化:(\w+)/.exec(content)?.[1] || '';

  if (!title) {
    console.log(`标题未匹配成功: ${title} |  ${dataIndex} | ${type}`)
  }
  const data: IColumn & { [key: string]: any } =  {
    title: title?.trim(),
    dataIndex: dataIndex.trim(),
    sortable: isSort !== 'false',
    width: Number(width),
    fixed: isFixed === 'true' ? 'left' : null,
    _type: type,
    _dataType: dataType,
    relationKey,
  };

  // 配置格式器
  if (formatter) {
    data._formatter = formatter
  }

  if (dataIndex !== labelKey) {
    data._labelKey = labelKey;
  }

  if (color) {
    data.color = color;
  }

  //  固定列,动态添加disabled属性
  if (disabled === 'true') {
    data._disabled = true;
  }
  
  return data
}

function parserCategory(data) {
  if (/\d+/.test(data[1])) {
    const [categoryLabel, categoryValue, categoryType, dataType, statisticsType] = data
    return {
      categoryLabel,
      categoryValue: Number(categoryValue),
      categoryType,
      dataType,
      statisticsType
    }
  }
  const [categoryLabel, categoryType, dataType, statisticsType] = data
  return {
    categoryLabel,
    categoryType,
    dataType,
    statisticsType
  }

}

export function groupParser(data:string, lineNum: number) {
  // 取数据首行为分类，第二行为数据
  const firstSplitIndex = data.indexOf('\n');
  const categoryArr = data
    .slice(0, firstSplitIndex)
    .split(',');

    const { categoryLabel, categoryValue, categoryType, dataType, statisticsType } = parserCategory(categoryArr)
  const content = data.slice(firstSplitIndex + 1);


  const contentData = content
  .split('\n')
  .map((item) => {
    const res = contentParser(item, categoryValue || lineNum);
    return res
  });

  const categoryData: ICategoryItem = {
    label: categoryLabel,
    value: categoryValue || lineNum,
    category: categoryType as ICategoryItem['category'],
    dataType: (dataType || defaultDataType) as ICategoryItem['dataType'],
    statisticsType: statisticsType as ICategoryItem['statisticsType'],
  };

  return {
    categoryData,
    contentData
  };
}
